import React, { useEffect, useState } from "react";
import Header from "./Components/Header";
import Input from "./Components/Input";
import TodoList from "./Components/Todo/TodoList";
import "./Styles/page.css";
import { readStorage, todoListSort, writeStorage } from "./utils";

export default function App() {
  const [listData, setListData] = useState<TodoListData>();
  window.onload = () => setListData(todoListSort(readStorage())); // 必须使用onload 使用useEffect会导致死循环

  // 在useEffect中写入，保证每次state刷新组件时都保存到storage中
  useEffect(() => {
    if (listData !== undefined) {
      writeStorage(listData);
    }
  });

  const submitHandler = (data: ITodo) => {
    if (listData !== undefined) {
      const copy = listData.slice(); // 浅拷贝产生一个新数组
      copy.push(data);
      setListData(todoListSort(copy));
    }
  };

  const dataChangeHandler = (data: TodoListData) => {
    setListData(todoListSort(data)); // 每次改变数据都进行一次排序
  };

  return (
    <div className="page-container">
      <Header />
      <Input onSubmit={submitHandler} />
      <TodoList data={listData} onDataChange={dataChangeHandler} />
    </div>
  );
}
